package com.benyq.networkprogramme

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.view.menu.MenuBuilder
import android.support.v7.widget.LinearLayoutManager
import android.util.EventLog
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.benyq.networkprogramme.base.adapter.BenyqBaseAdapter
import com.benyq.networkprogramme.base.bean.MsgEvent
import com.benyq.networkprogramme.base.bean.SimpleFriendBean
import com.benyq.networkprogramme.ftp.FtpHelper
import com.benyq.networkprogramme.tcp.OnReceivedListener
import com.benyq.networkprogramme.tcp.TcpService
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {

    // 退出时间
    private var currentBackPressedTime: Long = 0
    // 退出间隔
    private val BACK_PRESSED_INTERVAL = 2000

    private val friendAdapter: FriendAdapter by lazy { FriendAdapter(this) }

    private var executorService: ExecutorService = Executors.newSingleThreadExecutor()

    private lateinit var tcpBinder: TcpService.TcpServiceBinder

    private val friendResult = 1
    private val permissionRequest = 2

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {
        }

        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            tcpBinder = p1 as TcpService.TcpServiceBinder
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        checkPermission()
        initView()
        Intent(this, TcpService::class.java).run {
            startService(this)
        }


    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toolbar, menu)
        return super.onCreateOptionsMenu(menu)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        when (item.itemId) {
            R.id.action_search -> {
                startActivity(Intent(this, WebViewActivity::class.java))
            }
            R.id.action_email -> {
                startActivity(Intent(this, EmailActivity::class.java))
            }
            R.id.action_friend -> {
                startActivityForResult(Intent(this, AddFriendActivity::class.java), friendResult)
            }
            R.id.action_ftp -> {
                startActivity(Intent(this, FtpActivity::class.java))
            }
        }

        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == friendResult) {
            if (resultCode == Activity.RESULT_OK) {
                Log.e("susan", "fdfdfdfd")
                data?.run {
                    val ip = getStringExtra("ipAddress")
                    val port = getIntExtra("port", -1)
                    val name = getStringExtra("name")
                    val simpleFriendBean = SimpleFriendBean()
                    with(simpleFriendBean) {
                        this.name = name
                        this.ip = ip
                        this.port = port
                        Log.e("susan", this.toString())
                        friendAdapter.add(this)
                    }
                }
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            permissionRequest -> {
                grantResults.forEach {
                    if (it == PackageManager.PERMISSION_GRANTED){

                    }else if (it == PackageManager.PERMISSION_DENIED){
                        showToast("权限获取失败")
                        finish()
                        return@forEach
                    }
                }

            }
        }
    }


    override fun onDestroy() {
        unbindService(serviceConnection)
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


    @SuppressLint("RestrictedApi")
    override fun onPrepareOptionsPanel(view: View?, menu: Menu?): Boolean {
        if (menu != null) {
            if (menu.javaClass == MenuBuilder::class.java) {
                try {
                    val m = menu.javaClass.getDeclaredMethod("setOptionalIconsVisible", java.lang.Boolean.TYPE)
                    m.isAccessible = true
                    m.invoke(menu, true)
                } catch (e: Exception) {
                    Log.i("tag", "onPrepareOptionsPanel: " +
                            javaClass.simpleName +
                            "onMenuOpened...unable to set icons for overflow menu"
                            + e)
                }

            }
        }
        return super.onPrepareOptionsPanel(view, menu)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
                currentBackPressedTime = System.currentTimeMillis()
                showToast("再按一次退出程序")
                return true
            } else {
                finish()
            }
        }
        return super.dispatchKeyEvent(event)
    }

    private fun initView() {
        mainToolbar.popupTheme = R.style.PopupMenu
        setSupportActionBar(mainToolbar)

        rvFriend.layoutManager = LinearLayoutManager(this)
        friendAdapter.setOnItemClickListener(object : BenyqBaseAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                with(Intent(this@MainActivity, ChatActivity::class.java)) {
                    val friendBean = friendAdapter.datas[position]
                    putExtra("name", friendBean.name)
                    putExtra("ipAddress", friendBean.ip)
                    putExtra("port", friendBean.port)
                    startActivity(this)
                }
            }

        })
        friendAdapter.setOnItemLongClickListener(object : BenyqBaseAdapter.OnItemLongClickListener {
            override fun onItemLongClick(view: View, position: Int) {
                friendAdapter.remove(position)
            }
        })
        rvFriend.adapter = friendAdapter
        friendAdapter.add(SimpleFriendBean("Susan", "总在阳光下见到你", Date()))
    }

    fun checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return
        }
        val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        val permissionList = mutableListOf<String>()
        permissions.forEach {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(it)
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventReceived(msgEvent: MsgEvent) {
        val friendBean = friendAdapter.datas[0]
        friendBean.msg = msgEvent.msg
        friendBean.time = Date()
        Log.e("susan", friendBean.toString())
        friendAdapter.notifyDataSetChanged()
    }

}
